import React from 'react';
import { Icon, Input, Button } from 'antd';
import moment from 'moment';
import _ from 'lodash';
import cass from 'classnames';
import s from './index.module.less';
import ChatListItem from '../../components/ChatListItem';
import CloseBar from '../../components/CloseBar';
import Avatar from '../../components/Avatar';
import userServer from '../../services/user';
import config from '../../config';

const { baseUrl } = config;
const { globalSearch, globalSearchChatList, globalSearchChatListDetail } = userServer;

function replaceFun(str, keyword) {
    if (str.indexOf(keyword) > -1) {
        const newStr = str.replace(keyword, `<font color="#1890ff">${keyword}</font>`);
        return newStr;
    } else return str;
}

function getMsgText(elems) {
    const msgObj = {
        text: '',
        imgs: []
    };
    if (!elems) return msgObj;

    let msgs = elems;
    if (_.isString(elems)) msgs = JSON.parse(elems);

    if (msgs.length) {
        msgs.forEach(e => {
            // 因为@消息和1账号文件提醒的消息都是TIMCustomElem这个类型
            msgObj.type = e.msgType;
            if (e.msgType === 'TIMCustomElem') {
                if (e.msgContent.Desc !== 'file' && e.msgContent.Desc !== 'customer') {
                    msgObj.text += e.msgContent.Desc;
                } else if (e.msgContent.Desc === 'customer') {
                    // 新加字段为了做文件已读未读问题 暂不处理
                } else {
                    msgObj.newfilename = e.msgContent.Ext; // newfilename.extension
                }
            } else if (e.msgType === 'TIMLocationElem') {
                msgObj.text += JSON.parse(e.msgContent.Desc).address;
                msgObj.location = JSON.parse(e.msgContent.Desc);
            } else if (e.msgType === 'TIMImageElem') {
                msgObj.imgs.push(e.msgContent.ImageInfoArray[0].url);
            } else if (e.msgType === 'TIMSoundElem') {
                msgObj.text = '暂不支持语音信息';
            } else {
                msgObj.text += e.msgContent.Text;
            }
        });
    }
    return msgObj;
}

function handleList(res) {
    const list = (res.data || []).map(v => ({
        ...v,
        content: v.content,
        sendername: v.senderid === 1 ? '系统通知' : v.sendername,
    }));
    return list;
}

class ChatRecord extends React.Component {

    constructor(props) {
        super(props);
        const remote = window.electron.remote;
        const store = remote.getGlobal('store');
        const globalSearchParams = store.get('globalSearchParams');
        const { searchkey, groupid } = globalSearchParams;
        this.state = {
            list: [],
            chatList: [],
            chatDetailList: [],
            searchInputValue: searchkey,
            searchkey,
            groupid,
        }
        this.queryList(searchkey);
        this.getSearchList(globalSearchParams);
    }

    onScroll = async (e) => {
        const { active, chatDetailList } = this.state;
        if (active) {
            const { scrollTop, offsetHeight, scrollHeight } = e.target;
            // 上拉
            if (!this.loading && !this.isLoadNewEnd && scrollTop + offsetHeight > scrollHeight - 100) {
                this.loading = true;
                const { groupid, msgseq } = chatDetailList[chatDetailList.length - 1];
                const res = await globalSearchChatListDetail({ groupid, msgseqbegin: msgseq + 1, msgseqend: msgseq + 11 });
                if (res && res.data && res.data.length) {
                    const newList = handleList(res);
                    this.loading = false;
                    this.setState({ chatDetailList: [...chatDetailList, ...newList] });
                } else {
                    this.loading = false;
                    this.isLoadNewEnd = true;
                }
            } else if (!this.loading && !this.isLoadPassEnd && scrollTop < 100) { // 下拉
                this.loading = true;
                const { groupid, msgseq } = chatDetailList[0];
                const msgseqbegin = msgseq - 10 < 1 ? 1 : msgseq - 10;
                const res = await globalSearchChatListDetail({ groupid, msgseqbegin, msgseqend: msgseq });
                if (res && res.data && res.data.length) {
                    const passList = handleList(res);
                    this.loading = false;
                    this.setState({ chatDetailList: [...passList, ...chatDetailList] });
                } else {
                    this.loading = false;
                    this.isLoadPassEnd = true;
                }
            }
        }
    }

    onTransitionEnd = () => {
        // 列表跟新完成后，把当前activeItem滚动到列表顶部
        const recid = this.needScrollIntoViewChatId;
        const viewNode = this[`chat-${recid}`];
        if (recid && viewNode) {
            viewNode.scrollIntoView({ behavior: 'smooth', block: 'center' });
            this.needScrollIntoViewChatId = undefined; // 屏蔽了每次渲染都会把activeItem滚动到列表顶部
        }
    }

    queryList = async (searchkey) => {
        this.setState({ loading: true });
        const res = await globalSearch({ searchkey, pageindex: 1, pagesize: 99999 });
        if (res && res.chats) {
            const list = res.chats.dataList || [];
            this.setState({ list, loading: false });
            return;
        }
        this.setState({ loading: false });
    }

    getSearchList = async (globalSearchParams) => {
        this.setState({ loading: true });
        const res = await globalSearchChatList(globalSearchParams);
        if (res && res.data) {
            const chatList = handleList(res);
            this.setState({ chatList })
        }
        this.setState({ loading: false });
    }

    onChange = (e) => {
        this.setState({ searchInputValue: e.target.value });
    }

    onClose = () => {
        const remote = window.electron.remote;
        const store = remote.getGlobal('store');
        const globalSearchParams = store.get('globalSearchParams');
        const { searchkey, groupid } = globalSearchParams;
        this.setState({ searchInputValue: searchkey, searchkey, groupid });
        this.queryList(searchkey);
        this.getSearchList(globalSearchParams);
    }

    onPressEnter = (e) => {
        const searchkey = e.target.value;
        this.setState({ searchkey, groupid: undefined, chatList: [], chatDetailList: [] })
        this.queryList(searchkey);
    }

    onChatClick = (...params) => {
        const groupid = params[1].groupid;
        this.setState({
            groupid, loading: true, active: false
        }, () => {
            const { searchkey } = this.state;
            this.getSearchList({ searchkey, groupid });
        })
    }

    intoChatPage = () => {
        const { ipcRenderer } = window.electron;
        const { groupid } = this.state;
        ipcRenderer.send('set-goPage', { index: 0, data: { chatgroupid: groupid }, isChild: true });
    }

    viewDetail = async ({ groupid, msgseq, recid }) => {
        this.isLoadNewEnd = false;
        this.isLoadPassEnd = false;
        const msgseqbegin = msgseq - 10 < 1 ? 1 : msgseq - 10;
        const res = await globalSearchChatListDetail({ groupid, msgseqbegin, msgseqend: msgseq + 10 });
        if (res && res.data) {
            const chatDetailList = handleList(res);
            this.needScrollIntoViewChatId = recid;
            this.setState({ active: true, chatDetailList });
        }
    }

    onBack = () => {
        this.setState({ active: false, chatDetailList: [] });
    }

    onViewFile = (newfilename, text) => {
        if (!newfilename) return;

        let filename = text.split('文件:')[1];
        if (filename && filename.indexOf('到文件夹') > 0) {
            filename = text.split('到文件夹')[0];
        }

        const { ipcRenderer } = window.electron;
        ipcRenderer.send("preview", { filename, newfilename, url: `${baseUrl}/file/${newfilename}` });
    }

    renderMsg = (elems) => {
        const { searchkey } = this.state;
        const msgObj = getMsgText(elems);
        const { text, type, newfilename } = msgObj;
        if (type === 'TIMImageElem' || type === 'TIMLocationElem') {
            return <div>暂不支持暂时当前消息类型</div>
        };
        return (
            <div
                className={cass(s.text, { [s.under]: !!newfilename })}
                onClick={() => this.onViewFile(newfilename, text)}
                dangerouslySetInnerHTML={{ __html: replaceFun(text, searchkey) }}
            />
        )
    }

    renderChatList = (list, canNext) => {
        return (
            <div className={s.rightContent} onScroll={this.onScroll}>
                {list.map(v => (
                    <div
                        ref={d => this[`chat-${v.recid}`] = d}
                        key={v.recid}
                        className={s.item}
                    >
                        <Avatar
                            username={v.sendername}
                            headimage={v.headimage}
                            color={'userColor'}
                            borderColor={'userBorderColor'}
                        />
                        <div className={s.itemRight}>
                            <div className={s.name}>
                                {v.sendername}
                                {v.msgtime ? <div>{moment(v.msgtime * 1000).format('YYYY/MM/DD')}</div> : null}
                                {canNext ? <Button type="link" onClick={() => this.viewDetail(v)}>查看上下文</Button> : null}
                            </div>
                            {this.renderMsg(v.msgcontent)}
                        </div>
                    </div>
                ))}
            </div>
        )
    }

    render() {
        const { list, searchkey, searchInputValue, groupid, chatList, chatDetailList, active } = this.state;
        return (
            <div className={s.chatrecord}>
                <div className={s.dragbar}>
                    <CloseBar isChild />
                    查找聊天记录
                </div>
                <div className={s.header}>
                    <Input
                        value={searchInputValue}
                        onChange={this.onChange}
                        placeholder="请输入关键字"
                        prefix={<Icon type="search" />}
                        suffix={<Icon type="close-circle" onClick={this.onClose} />}
                        onPressEnter={this.onPressEnter}
                    />
                </div>
                <div className={s.content}>
                    <div className={s.left}>
                        {list.map((v, i) => (
                            <ChatListItem
                                innerRef={(d, id) => this[`node-${id}`] = d}
                                key={`chatItem${i}`}
                                activeGroupid={groupid}
                                data={v}
                                onClick={this.onChatClick}
                                replaceFun={(str) => replaceFun(str, searchkey)}
                            />
                        ))}
                    </div>
                    {chatList && chatList.length ? (
                        <div
                            className={cass(s.rightWrap, { [s.active]: active })}
                            ref={d => this.moveRef = d}
                            onTransitionEnd={this.onTransitionEnd}
                        >
                            <div className={s.right}>
                                <div className={s.rightHeader}>
                                    {`${chatList.length}条与“${searchkey}”的相关的搜索结果`}
                                    <div onClick={this.intoChatPage} >
                                        <span className="mdi mdi-chat-outline" />
                                    进入聊天
                                </div>
                                </div>
                                {this.renderChatList(chatList, true)}
                            </div>
                            <div className={s.rightright}>
                                <div className={s.righttop}>
                                    <Button
                                        icon="left"
                                        type="link"
                                        onClick={this.onBack}
                                    >
                                        返回
                                </Button>
                                </div>
                                {this.renderChatList(chatDetailList)}
                            </div>
                        </div>
                    ) : null}
                </div>
            </div>
        )
    }
}

export default ChatRecord